package com.seednia.module.core.search.util;

import java.util.HashMap;
import java.util.Map;

import com.seednia.foundation.framework.dto.AbstractRecord;
import com.seednia.foundation.framework.dto.ICriteria;
import com.seednia.foundation.framework.dto.QueryParams;

public class QueryBuilderFactory {
	
	public static final String SPECIFIER_KEY = "specifier";
	
	private Map<String, AbstractQueryBuilder> queryBuilderMap = new HashMap<String, AbstractQueryBuilder>();
	
	private static QueryBuilderFactory _instance = new QueryBuilderFactory();
	
	private QueryBuilderFactory()
	{
	}
	
	public static QueryBuilderFactory getInstance()
	{
		return _instance; 
	}
	
	public void register(Class<? extends ICriteria> criteriaClass, String specifier, AbstractQueryBuilder queryBuilder)
	{
		if (specifier== null)
			specifier = "";
		this.queryBuilderMap.put(criteriaClass.getSimpleName()+specifier, queryBuilder);
	}
	
	public final AbstractQueryBuilder getQueryBuilder(Class<? extends ICriteria> criteriaClass, String specifier)
	{
		if (specifier== null)
			specifier = "";
		return this.queryBuilderMap.get(criteriaClass.getSimpleName()+specifier);
	}

	/**
	 * Gets the related query builder and creates the query builder
 	 * @param record
	 * @param specifier
	 * @return
	 */
	public String createQueryString(ICriteria criteria, QueryParams params)
	{
		String specifier = (params != null) ? (String)params.get(SPECIFIER_KEY, "") : "";
		AbstractQueryBuilder abstractQueryBuilder = this.getQueryBuilder(criteria.getClass(), specifier);
				
		if (abstractQueryBuilder != null)
			return abstractQueryBuilder.buildQueryString(criteria);
		else 
			throw new IllegalArgumentException("AbstractQueryBuilder ["+criteria.getClass().getSimpleName()+specifier+"] was not found.");
	}
}
